<?php

namespace App\Http\Controllers;

use App\Enums\RunErrandEnum;
use App\Helpers\ResponseHelper;
use App\Http\Requests\RunErrandRequest;
use App\Models\RunErrand;
use Illuminate\Http\Request;

class RunErrandController extends Controller
{
    public function apply(RunErrandRequest $request)
    {
        $user = $request->user();
        $runErrand = RunErrand::where('user_id', $user->id)->first();
        if ($runErrand) {
            if ($runErrand->status == RunErrandEnum::PENDING) {
                return ResponseHelper::error(message: '正在审核,请勿重复提交');
            }
            if ($runErrand->status == RunErrandEnum::SUCCESS) {
                return ResponseHelper::error(message: '您的请求已经审核通过,请勿重复提交');
            }
            $runErrand->nick_name = $request->input('nick_name');
            $runErrand->mobile = $request->input('mobile');
            $runErrand->school_id = $request->input('school_id');
            $runErrand->faculty_id = $request->input('faculty_id');
            $runErrand->specialty = $request->input('specialty');
            $runErrand->id_number = $request->input('id_number');
            $runErrand->id_card_front = $request->input('id_card_front');
            $runErrand->id_card_reverse_side = $request->input('id_card_reverse_side');
            $runErrand->status = RunErrandEnum::PENDING;
            $runErrand->save();
        } else {
            RunErrand::create([
                'user_id' => $user->id,
                'nick_name' => $request->input('nick_name'),
                'mobile' => $request->input('mobile'),
                'school_id' => $request->input('school_id'),
                'faculty_id' => $request->input('faculty_id'),
                'specialty' => $request->input('specialty'),
                'id_number' => $request->input('id_number'),
                'id_card_front' => $request->input('id_card_front'),
                'id_card_reverse_side' => $request->input('id_card_reverse_side'),
            ]);
        }
        return ResponseHelper::success();
    }

    public function detail(Request $request)
    {
        $user = $request->user();
        $runErrand = RunErrand::with(['school', 'faculty'])->where('user_id', $user->id)->first();
        if (!$runErrand) {
            return ResponseHelper::error(message: '您还没有申请跑腿');
        }
        return ResponseHelper::success($runErrand);
    }
}
